package cn.edu.csmzxy.rk233x.auth_system.controller;

import cn.edu.csmzxy.rk233x.auth_system.dto.ResultDTO;
import cn.edu.csmzxy.rk233x.auth_system.dto.UserRoleDTO;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysRole;
import cn.edu.csmzxy.rk233x.auth_system.service.SysUserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

/**
 * @author wumxing
 * @date 2025/10/15 17:06
 * @description  用户-角色关联管理接口
 */

@Tag(name = "用户-角色关联接口", description = "用户角色分配")
@RestController
@RequestMapping("/api/sys/user-role")
@SecurityRequirement(name = "JWT")
public class SysUserRoleController {

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Operation(summary = "查询用户已分配角色", description = "需要user:role:query权限")
    @PreAuthorize("hasAuthority('user:role:query')")
    @GetMapping("/user/{userId}")
    public ResultDTO<List<SysRole>> getRolesByUserId(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        return ResultDTO.success(sysUserRoleService.getRolesByUserId(userId));
    }

    @Operation(summary = "分配用户角色", description = "需要user:role:assign权限")
    @PreAuthorize("hasAuthority('user:role:assign')")
    @PostMapping("/assign")
    public ResultDTO<?> assignRoles(@Valid @RequestBody UserRoleDTO userRoleDTO) {
        sysUserRoleService.assignRoles(userRoleDTO.getUserId(), userRoleDTO.getRoleIds());
        return ResultDTO.success("角色分配成功");
    }
}

